package com.shadowlight.hero_story.cmdHandler;

import com.shadowlight.hero_story.msg.GameMsgProtocol;
import com.shadowlight.hero_story.pojo.UserRepository;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description 用户获取其他在线用户处理器
 * @Author cz
 * @Date 2022/3/2
 */
@Slf4j
public class WhoElseIsHereCmdHandler implements ICmdHandler<GameMsgProtocol.WhoElseIsHereCmd> {

    @Override
    public void handle(ChannelHandlerContext channelHandlerContext, GameMsgProtocol.WhoElseIsHereCmd msg) {
        GameMsgProtocol.WhoElseIsHereResult.Builder whoElseIsHereResultBuilder = GameMsgProtocol.WhoElseIsHereResult.newBuilder();
        //返回了所有当前在线用户，没有附带用户的位置信息
        //to do moveState
        UserRepository.getInstance().getAll().forEach(o -> {
            GameMsgProtocol.WhoElseIsHereResult.UserInfo.Builder userInfoBuilder = GameMsgProtocol.WhoElseIsHereResult.UserInfo.newBuilder();
            userInfoBuilder.setUserId(o.getId());
            userInfoBuilder.setUserName(o.getUserName());
            userInfoBuilder.setHeroAvatar(o.getHeroAvatar());
            if (o.getMoveState() != null) {
                GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState.Builder moveStateBuilder = GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState.newBuilder();
                moveStateBuilder.setFromPosX(o.getMoveState().getMoveFromPosX());
                moveStateBuilder.setFromPosY(o.getMoveState().getMoveFromPosY());
                moveStateBuilder.setToPosX(o.getMoveState().getMoveToPosX());
                moveStateBuilder.setToPosY(o.getMoveState().getMoveToPosY());
                moveStateBuilder.setStartTime(o.getMoveState().getStartTime());
                userInfoBuilder.setMoveState(moveStateBuilder.build());
            }
            whoElseIsHereResultBuilder.addUserInfo(userInfoBuilder.build());
        });
        channelHandlerContext.writeAndFlush(whoElseIsHereResultBuilder.build());
    }
}
